<?php
// +----------------------------------------------------------------------
// | 海豚PHP框架 [ DolphinPHP ]
// +----------------------------------------------------------------------
// | 版权所有 2016~2017 河源市卓锐科技有限公司 [ http://www.zrthink.com ]
// +----------------------------------------------------------------------
// | 官方网站: http://dolphinphp.com
// +----------------------------------------------------------------------
// | 开源协议 ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------

namespace app\warehouse\admin;

use app\admin\controller\Admin;
use app\common\builder\ZBuilder;
use app\warehouse\model\WareHouse as WareHouseModel;
use think\Db;

/**
 * 仓库管理控制器
 * @package app\warehouse\controller
 */
class Index extends Admin
{
    /**
     * 仓库列表
     * @author 陈梦晨 <2391157750@qq.com>
     * @return mixed
     */
    public function index()
    {
       // 查询
        $map = $this->getMap();
        $map['isdel']=0;
        $pagetitle="仓库列表";

        // 排序
        $order = $this->getOrder('sort desc, warehouseid asc');
        // 数据列表
        $data_list = WareHouseModel::getAll($map, $order);
        foreach ($data_list as $key => $value) {
            # code...
            $data_list[$key]['address']=getarea($value['provinceid'],$value['cityid'],$value['townid']).$value['area'];
        }
        // 分页数据
        $page = $data_list->render();

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle($pagetitle) // 设置页面标题
            ->setPrimaryKey("warehouseid")
            ->setSearch(['warehousename' => '仓库名称']) // 设置搜索框
            ->addTimeFilter('create_time')
            ->addTopButton('add') // 添加顶部按钮
            ->addTopButton('enable') // 添加顶部按钮
            ->addTopButton('disable') // 添加顶部按钮
            ->addColumns([ // 批量添加数据列
                ['warehouseid', '编号'],
                ['code', '仓库编码', 'text.edit'],
                ['warehousename', '仓库名称', 'text.edit'],
                ['address','仓库地址'],
                ['sort', '排序', 'text.edit'],
                ['status', '状态', 'switch'],
                ['create_time', '添加时间'],
                ['right_button', '操作', 'btn']
            ])
            ->addOrder(['sort', 'warehouseid'])
            ->addRightButton('edit', ['class'=>'btn btn-xs btn-default','icon' => 'fa fa-fw fa-navicon', 'title' => '设置配送区域', 'href' => url('DeliveryArea/index', ['id' => '__id__'])],true)
            ->addRightButton('edit', ['class'=>'btn btn-xs btn-default','icon' => 'fa fa-fw fa-truck', 'title' => '查看运费设置', 'href' => url('Freight/index', ['id' => '__id__'])])
            ->addRightButton('edit', ['class'=>'btn btn-xs btn-default','icon' => 'fa fa-pencil', 'title' => '编辑', 'href' => url('edit', ['id' => '__id__'])])
            ->addRightButton('delete',['class'=>'btn btn-xs btn-default','icon' => 'fa fa-times', 'title' => '删除', 'href' => url('delete', ['id' => '__id__'])])
            ->setRowList($data_list) // 设置表格数据
            ->setPages($page) // 设置分页数据
            ->fetch(); // 渲染模板
    }

    /**
     * 编辑仓库
     * @param null $id 仓库id
     * @author 陈梦晨 <2391157750@qq.com>
     */
    public function edit($id = null)
    {
        if ($id === null) return $this->error('缺少参数');
        $info = WareHouseModel::find(['warehouseid' => $id]);
        $list_province = db("admin_area")->where("pid=0")->column("id,name");
        $list_city = db("admin_area")->where("pid=".$info['provinceid'])->column("id,name");
        $list_town = db("admin_area")->where("pid=".$info['cityid'])->column("id,name");
        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('编辑') // 设置页面标题
            ->setUrl(url('dosave'))
            ->addFormItems([ // 批量添加表单项
                ['hidden', 'warehouseid'],
                ['text', 'warehousename', '仓库名称', '<span class="text-danger">必填</span>'],
                ['text', 'code', '仓库编码', '<span class="text-danger">必填</span>'],
                ['linkage', 'provinceid','选择省份','<span class="text-danger">必选</span>',$list_province,'', url('get_city'), 'cityid,townid'],
                ['linkage', 'cityid','选择城市','<span class="text-danger">必选</span>',$list_city, '',url('get_area'), 'townid'],
                ['select', 'townid','选择地区','<span class="text-danger">必选</span>',$list_town],
                ['text', 'area', '详细地址'],
                ['textarea', 'remark', '简介备注'],
                ['radio', 'status', '状态', '', ['禁用', '启用']],
                ['text', 'sort', '排序'],
            ])
            ->layout(['warehousename'=>6,'code'=>6,'provinceid'=> 4,'cityid'=>4,'townid'=>4,'sort'=>4])
            ->setFormData($info) // 设置表单数据
            ->fetch();
            
    }
    public function dosave(){
        // 保存数据
        if ($this->request->isPost()) {
            $data = $this->request->post();
            
            // 验证
            $result = $this->validate($data, 'WareHouse');
            // 验证失败 输出错误信息
            if(true !== $result) return $this->error($result);

            if ($menu = WareHouseModel::update($data)) {
                return $this->success('修改成功', url('index'));
            } else {
                return $this->error('修改失败');
            }
        }
    }
    /**
     * 新增仓库
     * @author 陈梦晨 <2391157750@qq.com>
     */

    public function add(){
        $list_province = db("admin_area")->where("pid=0")->column("id,name");
        // 使用ZBui lder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('新增') // 设置页面标题
            ->setUrl(url('doadd'))
            ->addFormItems([ // 批量添加表单项
                ['text', 'warehousename', '仓库名称', '<span class="text-danger">必填</span>'],
                ['text', 'code', '仓库编码', '<span class="text-danger">必填</span>'],
                ['linkage', 'provinceid','选择省份','<span class="text-danger">必选</span>',$list_province,'', url('get_city'), 'cityid,townid'],
                ['linkage', 'cityid','选择城市','<span class="text-danger">必选</span>','', '',url('get_area'), 'townid'],
                ['select', 'townid','选择地区','<span class="text-danger">必选</span>'],
                ['text', 'area', '详细地址'],
                ['textarea', 'remark', '简介备注'],
                ['radio', 'status', '状态', '', ['禁用', '启用'],1],
                ['text', 'sort', '排序'],
            ])
            ->layout(['warehousename'=>6,'code'=>6,'provinceid'=> 4,'cityid'=>4,'townid'=>4,'sort'=>4])
            ->fetch();
    }
    public function doadd(){
        // 保存数据
        if ($this->request->isPost()) {
            $data = $this->request->post();
            // 验证
            $result = $this->validate($data, 'WareHouse');
            // 验证失败 输出错误信息
            if(true !== $result) return $this->error($result);

            if ($menu = WareHouseModel::create($data)) {
                return $this->success('新增成功', url('index'));
            } else {
                return $this->error('新增失败');
            }
        }

    }

    /**
     * 删除仓库
     * @author 陈梦晨 <2391157750@qq.com>
     * @return mixed
     */
    public function delete($record = [])
    {
        $id = $this->request->param('id');
        // 删除节点
        if (WareHouseModel::del($id)) {
            return $this->success('删除成功');
        } else {
            return $this->error('删除失败');
        }
    }
    /**
     * 设置状态
     * @param string $type 状态类型:enable/disable
     * @param array $record 行为日志内容
     * @author 陈梦晨 <2391157750@qq.com>
     * @return mixed
     */
    public function setstatus($type = '', $record = [])
    {
        $ids = $this->request->isPost() ? input('post.ids/a') : input('param.ids');
        if (empty($ids)) return $this->error('缺少主键');

        if(WareHouseModel::$type($ids)){
            return $this->success('操作成功');
        }else{
            return $this->error('操作失败');
        }
            
    }

    /**
     * 禁用
     * @param array $record 行为日志内容
     * @author 陈梦晨 <2391157750@qq.com>
     * @return mixed
     */
    public function disable($record = [])
    {
        return $this->setstatus('disable');
    }

    /**
     * 启用
     * @param array $record 行为日志内容
     * @author 陈梦晨 <2391157750@qq.com>
     * @return mixed
     */
    public function enable($record = [])
    {
        return $this->setstatus('enable');
    }

    public function get_city($provinceid = '') {
        $result = db("admin_area")->where("pid=" . $provinceid)->field("id,name")->select();
        $list=[];
        foreach ($result as $key => $value) {
            # code...
            $list[$key]['key']=$value['id'];
            $list[$key]['value']=$value['name'];
        }
        
        $arr['code'] = '1'; //判断状态
        $arr['msg'] = '请求成功'; //回传信息
        $arr['list'] = $list; //数据
        return json($arr);
    }

    public function get_area($cityid = '') {
        $result = db("admin_area")->where("pid=" . $cityid)->field("id,name")->select();
        $list=[];
        foreach ($result as $key => $value) {
            # code...
            $list[$key]['key']=$value['id'];
            $list[$key]['value']=$value['name'];
        }
        
        $arr['code'] = '1'; //判断状态
        $arr['msg'] = '请求成功'; //回传信息
        $arr['list'] = $list; //数据
        return json($arr);
    }
}